package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"trace-rule/internal/handler"
	"trace-rule/internal/repository"
	"trace-rule/internal/service"
	"trace-rule/pkg/config"
	"trace-rule/pkg/database"

	"github.com/gin-gonic/gin"
)

func getCurrentDirectory() string {
	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	return dir
}

func main() {
	// 加载配置
	if err := config.LoadConfig(); err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	workDir := getCurrentDirectory()
	log.Printf("Working directory: %s", workDir)

	// 获取项目根目录（假设当前在 cmd 目录下）
	rootDir := filepath.Dir(workDir)
	log.Printf("Root directory: %s", rootDir)

	db, err := database.InitDB()
	if err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}

	ruleRepo := repository.NewRuleRepository(db)
	ruleService := service.NewRuleService(ruleRepo)
	priceMonitorService := service.NewPriceMonitorService(ruleService)
	priceMonitorService.StartMonitoring()
	ruleHandler := handler.NewRuleHandler(ruleService)

	r := gin.Default()

	// API 路由
	api := r.Group("/api")
	{
		rules := api.Group("/rules")
		{
			rules.POST("", ruleHandler.CreateRule)
			rules.PUT("/:id", ruleHandler.UpdateRule)
			rules.DELETE("/:id", ruleHandler.DeleteRule)
			rules.GET("/:id", ruleHandler.GetRule)
			rules.GET("", ruleHandler.ListRules)
			rules.GET("/enabled", ruleHandler.ListEnabledRules)
		}
	}

	// 静态文件服务 - 使用绝对路径
	webPath := filepath.Join(rootDir, "trace_ruler/web")
	r.Static("/static", filepath.Join(webPath, "static")) // 提供静态资源

	// 首页路由
	r.GET("/", func(c *gin.Context) {
		c.File(filepath.Join(webPath, "static", "index.html"))
	})

	r.GET("/prices.html", func(c *gin.Context) {
		c.File(filepath.Join(webPath, "static", "prices.html"))
	})

	if err := r.Run(fmt.Sprintf(":%d", config.GlobalConfig.Server.Port)); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
